﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Net.Mime;
using DAL;
using System.Collections.Generic;
using System.ComponentModel;
using Telerik.Web.UI;
using System.Globalization;



public partial class CSManager_UserControl_uc_LapPhieu_ChiTiet : System.Web.UI.UserControl
{
    public string _DSID;
    public DateTime _Ngay;
    public int _BuoiID;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            InitData();
        }
    }

    private void InitData()
    {
        hdfDateTime.Value = _Ngay.ToString("dd/MM/yyyy");
        hdfBuoiID.Value = _BuoiID.ToString();
        hdfDSID.Value = _DSID;
        lblAlerting.Text = string.Empty;
        lblNgay.Text = _Ngay.ToString("dd/MM/yyyy");
        lblBuoi.Text = GetBuoiName();
        CheckTonTai();


    }
    private void CheckTonTai()
    {
        DeliveryBO del = new DeliveryBO();

        int rs = del.Delivery_SO_CS_Check_New(DateTime.ParseExact(hdfDateTime.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture), int.Parse(hdfBuoiID.Value));
        if (rs > 0)
        {
            GetDeliveryByID();
            btnRefesh.Visible = false;
            btnSave.Visible = false;
        }
        else
        {
            GetDelivery();
            btnRefesh.Visible = true;
            btnSave.Visible = true;
        }

    }
    private string GetBuoiName()
    {
        CateRouteBO cate = new CateRouteBO();

        ZD_PRC_ZD_CATE_BUOI_GETBYIDResult result = new ZD_PRC_ZD_CATE_BUOI_GETBYIDResult();
        result = cate.BuoiGet_SingleLine(int.Parse(hdfBuoiID.Value));
        return result.TENBUOI;
    }

    private void GetDelivery()
    {
        DeliveryBO del = new DeliveryBO();

        List<ZD_PRC_ZD_DELIVERY_SO_TEMP_CS_MAN_GETBYIDResult> result = new List<ZD_PRC_ZD_DELIVERY_SO_TEMP_CS_MAN_GETBYIDResult>();
        result = del.Delivery_SO_Temp_Detail_CS_Man_GetByID(hdfDSID.Value);

        grdList.DataSource = result;
        grdList.DataBind();
        if (grdList.Rows.Count > 0)
        {
            //This replaces <td> with <th> and adds the scope attribute
            grdList.UseAccessibleHeader = true;

            //This will add the <thead> and <tbody> elements
            grdList.HeaderRow.TableSection = TableRowSection.TableHeader;

            //This adds the <tfoot> element. 
            //Remove if you don't have a footer row
            //gvTheGrid.FooterRow.TableSection = TableRowSection.TableFooter;
        }

    }

    private void GetDeliveryByID()
    {
        DeliveryBO del = new DeliveryBO();

        List<ZD_PRC_ZD_DELIVERY_SO_CS_MAN_GETBYIDResult> result = new List<ZD_PRC_ZD_DELIVERY_SO_CS_MAN_GETBYIDResult>();
        result = del.Delivery_SO_CS_Man_Get(DateTime.ParseExact(hdfDateTime.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture), int.Parse(hdfBuoiID.Value));

        grdList.DataSource = result;
        grdList.DataBind();

    }

    protected void btnRefesh_Click(object sender, EventArgs e)
    {
        lblAlerting.Text = string.Empty;
        RefeshRepeater();
    }
    private void RefeshRepeater()
    {
        try
        {
            DeliveryBO del = new DeliveryBO();
            List<ZD_PRC_ZD_TONG_HOP_CHECK_SL_ISBNResult> result = new List<ZD_PRC_ZD_TONG_HOP_CHECK_SL_ISBNResult>();
            result = del.CheckISBN();
            DataTable dataTable = new DataTable();
            dataTable = ConvertToDataTable(result);

            if (grdList.Rows.Count > 0)
            {
                for (int i = 0; i < grdList.Rows.Count; i++)
                {
                    int TongSoLuong = 0;
                    // Cell 9 la checkbox, cell 10 la textbox
                    string strISBN = ((Label)grdList.Rows[i].Cells[5].FindControl("lblListingISBN")).Text.Trim().Replace(",", "");
                    CheckBox chkSave = ((CheckBox)grdList.Rows[i].Cells[10].FindControl("chkSave"));
                    TextBox txtSOLUONG = ((TextBox)grdList.Rows[i].Cells[11].FindControl("txtSOLUONG"));
                    foreach (DataRow row in dataTable.Rows)
                    {
                        if (strISBN == row["ITEMCODE"].ToString())
                        {

                            row["TONGCONG"] = (int.Parse(Math.Round((decimal)row["TONGCONG"]).ToString()) - int.Parse(txtSOLUONG.Text.Trim().Replace(",", ""))).ToString();
                            ((Label)grdList.Rows[i].Cells[13].FindControl("lblListingTongTonKhoQ9")).Text = int.Parse(Math.Round((decimal)row["KHOQ9"]).ToString()).ToString();
                            ((Label)grdList.Rows[i].Cells[14].FindControl("lblListingCreditQ9")).Text = int.Parse(Math.Round((decimal)row["CREDITQ9"]).ToString()).ToString();
                            ((Label)grdList.Rows[i].Cells[15].FindControl("lblListingReverseQ9")).Text = int.Parse(Math.Round((decimal)row["RESERVEQ9"]).ToString()).ToString();
                            ((Label)grdList.Rows[i].Cells[16].FindControl("lblListingTongTonKhoQ1")).Text = int.Parse(Math.Round((decimal)row["KHOQ1"]).ToString()).ToString();
                            ((Label)grdList.Rows[i].Cells[17].FindControl("lblListingTongTonKhoHN")).Text = int.Parse(Math.Round((decimal)row["KHOHN"]).ToString()).ToString();
                            ((Label)grdList.Rows[i].Cells[18].FindControl("lblListingInTransit")).Text = int.Parse(Math.Round((decimal)row["INTRANSIT"]).ToString()).ToString();
                            ((Label)grdList.Rows[i].Cells[19].FindControl("lblListingPOOrders")).Text = int.Parse(Math.Round((decimal)row["POORDER"]).ToString()).ToString();
                            TongSoLuong += int.Parse(txtSOLUONG.Text.Trim());
                            row.EndEdit();
                            dataTable.AcceptChanges();
                            break;


                        }
                    }
                }

            }

            // update lai cot tong so luong vao GridView
            if (grdList.Rows.Count > 0)
            {
                for (int i = 0; i < grdList.Rows.Count; i++)
                {
                    // Cell 9 la checkbox, cell 10 la textbox
                    string strISBN = ((Label)grdList.Rows[i].Cells[5].FindControl("lblListingISBN")).Text.Trim().Replace(",", "");
                    CheckBox chkSave = ((CheckBox)grdList.Rows[i].Cells[10].FindControl("chkSave"));
                    TextBox txtSOLUONG = ((TextBox)grdList.Rows[i].Cells[11].FindControl("txtSOLUONG"));
                    foreach (DataRow row in dataTable.Rows)
                    {
                        if (strISBN == row["ITEMCODE"].ToString())
                        {

                            ((Label)grdList.Rows[i].Cells[12].FindControl("lblListingTongTonKho")).Text = int.Parse(Math.Round((decimal)row["TONGCONG"]).ToString()).ToString();
                            break;
                        }
                    }
                }

            }
        }
        catch
        {


        }
    }

    private DataTable ConvertToDataTable<ZD_PRC_ZD_TONG_HOP_CHECK_SL_ISBNResult>(List<ZD_PRC_ZD_TONG_HOP_CHECK_SL_ISBNResult> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(ZD_PRC_ZD_TONG_HOP_CHECK_SL_ISBNResult));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (ZD_PRC_ZD_TONG_HOP_CHECK_SL_ISBNResult item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            lblAlerting.Text = string.Empty;
            bool isSave = true;
            bool check = false;

            DateTime dtSearch = DateTime.ParseExact(lblNgay.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);

            //kiem tra xem la Ngay hom nay va buoi hom nay da duoc lap phieu xuat chua?
            DeliveryBO deli = new DeliveryBO();
            List<ZD_PRC_ZD_DELIVERY_SO_CS_CHECKResult> rsult = new List<ZD_PRC_ZD_DELIVERY_SO_CS_CHECKResult>();

            rsult = deli.Delivery_SO_CS_View(dtSearch, int.Parse(hdfBuoiID.Value), int.Parse(Session["UserID"].ToString()));

            if (rsult.Count <= 0)
            {

                for (int i = 0; i < grdList.Rows.Count; i++)
                {
                    // Cell 9 la checkbox, cell 10 la textbox
                    CheckBox chkSave = ((CheckBox)grdList.Rows[i].Cells[10].FindControl("chkSave"));
                    TextBox txtSOLUONG = ((TextBox)grdList.Rows[i].Cells[11].FindControl("txtSOLUONG"));

                    if ((chkSave.Checked) && int.Parse(txtSOLUONG.Text.Trim().Replace(",","")) > 0)
                    {
                        string strTSL = ((Label)grdList.Rows[i].Cells[8].FindControl("lblListingTSL")).Text.Trim().Replace(",", "");
                        string strSoLuong = ((TextBox)grdList.Rows[i].Cells[11].FindControl("txtSOLUONG")).Text.Trim().Replace(",", "");
                        if (int.Parse(strTSL) >= int.Parse(strSoLuong))
                        {
                            check = true;
                            break;
                        }
                    }
                }
                if (!check)
                {
                    lblAlerting.Text = "Không có dữ liệu lập phiếu xuất hoặc dữ liệu không đúng!";
                    return;
                }
                //   
                try
                {


                    DeliveryBO del = new DeliveryBO();

                    int masterId = 0;
                    // luu master
                    masterId = del.Delivery_SO_Insert(-1, int.Parse(hdfBuoiID.Value), dtSearch, int.Parse(Session["UserID"].ToString()));
                    if (masterId > 0)
                    {
                        for (int i = 0; i < grdList.Rows.Count; i++)
                        {
                            // Cell 9 la checkbox, cell 10 la textbox
                            CheckBox chkSave = ((CheckBox)grdList.Rows[i].Cells[10].FindControl("chkSave"));
                            string strTSL = ((Label)grdList.Rows[i].Cells[8].FindControl("lblListingTSL")).Text.Trim().Replace(",", "");
                            string strSoLuong = ((TextBox)grdList.Rows[i].Cells[11].FindControl("txtSOLUONG")).Text.Trim().Replace(",", "");

                            if ((chkSave.Checked) && int.Parse(strSoLuong) > 0)
                            {
                                if (int.Parse(strTSL) >= int.Parse(strSoLuong))
                                {
                                    string strROUTEID = ((HiddenField)grdList.Rows[i].Cells[0].FindControl("hdfROUTEID")).Value;
                                    string strKHOID = ((HiddenField)grdList.Rows[i].Cells[0].FindControl("hdfKHOID")).Value;
                                    string strMaKhachHang = ((Label)grdList.Rows[i].Cells[2].FindControl("lblListingMaKhachHang")).Text.Trim();
                                    string strSO = ((Label)grdList.Rows[i].Cells[4].FindControl("lblListingSO")).Text.Trim();
                                    string strISBN = ((Label)grdList.Rows[i].Cells[5].FindControl("lblListingISBN")).Text.Trim().Replace(",", "");
                                    string strKHOSACHID = ((HiddenField)grdList.Rows[i].Cells[7].FindControl("hdfKHOSACHID")).Value;
                                    string strNgayETD = ((Label)grdList.Rows[i].Cells[9].FindControl("lblListingNgayETD")).Text.Trim();
                                    DateTime dtime = DateTime.ParseExact(strNgayETD, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                                    int rs = del.Delivery_SO_Detail_Insert_Or_Update(-1, masterId, int.Parse(strROUTEID), strKHOID, strMaKhachHang, int.Parse(strSO), strISBN, strKHOSACHID, dtime, int.Parse(strTSL), int.Parse(strSoLuong), false, 0, int.Parse(Session["UserID"].ToString()), int.Parse(Session["UserID"].ToString()));
                                    if (rs <= 0)
                                    {
                                        isSave = false;
                                    }
                                }

                            }
                        }
                        if (!isSave)
                        {
                            lblAlerting.Text = "Lưu thất bại, bạn vui lòng thử lại!";
                            return;
                        }
                        else
                        {
                            btnRefesh.Visible = false;
                            btnSave.Visible = false;
                            lblAlerting.Text = "Lưu thành công!";
                            GetDeliveryByID();
                        }
                    }

                }
                catch
                {

                    lblAlerting.Text = "Lưu thất bại, bạn vui lòng thử lại!";
                    return;
                }

            }
            else
            {
                btnRefesh.Visible = false;
                btnSave.Visible = false;
            }
        }
        catch
        {


        }
    }
}
